package com.shu.qq.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.shu.qq.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class UserAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.info("访问资源受限，异常处理{}",accessDeniedException.getMessage());
        R<String> failed = new R<>(403, "资源访问受限，请先登录");
        String s = JSON.toJSONString(failed);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(s);
    }
}
